package dp.mobile.eden;

import java.util.Date;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import dp.mobile.comm.RestClient;
import dp.mobile.game.Score;
import dp.mobile.system.SoundManager;

public class SaveHighScoreAct extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.save_high_score);
		mLevelName			= this.getIntent().getExtras().getString(LEVEL_NAME_EXTRA);
		
		initComp();
		setListener();
	}
	
	private void initComp(){
		mNextBtn			= (Button) findViewById(R.id.highscore_next_btn);
		mHighScoreValue		= (TextView) findViewById(R.id.highscore_value);
		mFBShareBtn			= (Button) findViewById(R.id.fb_share_btn);
		mTwitterShareBtn	= (Button) findViewById(R.id.twitter_share_btn);
		mPostScoreBtn		= (Button) findViewById(R.id.post_score_btn);
		mPlayerNameEditTxt	= (EditText) findViewById(R.id.player_name_edit_txt);
		mLevelNameTextView	= (TextView) findViewById(R.id.level_name);
		
		mLevelNameTextView.setText(mLevelName);
		
		mScoreValue = this.getIntent().getExtras().getInt(Score.SCORE_EXTRA);
		mDateTaken	= new Date();
		
		mHighScoreValue.setText(String.valueOf(mScoreValue));
	}
	
	private void setListener(){
		mNextBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Next-level
				finish(); //Dummy action
			}
		});
		
		mPostScoreBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mPlayerName = mPlayerNameEditTxt.getText().toString();
				if(mPlayerName.equals("") || mPlayerName.equals("Enter your name"))
					Toast.makeText(getBaseContext(), "Please enter your name", 3000).show();
				else
					saveScore(mLevelName, mPlayerName, mScoreValue, mDateTaken);
			}
		});
		
		if(mFBShareBtn != null){
			mFBShareBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent1 = new Intent(SaveHighScoreAct.this.getApplicationContext(), FacebookAct.class);
					intent1.putExtra(GameActivityBase.LEVEL_EXTRAS, mLevelName);
					intent1.putExtra(GameActivityBase.SCORE_EXTRAS, mScoreValue);
					startActivity(intent1);
				}
			});
		}
		
		if(mTwitterShareBtn != null){
			mTwitterShareBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent1 = new Intent(SaveHighScoreAct.this.getApplicationContext(), TwitterAct.class);
					intent1.putExtra(GameActivityBase.LEVEL_EXTRAS, mLevelName);
					intent1.putExtra(GameActivityBase.SCORE_EXTRAS, mScoreValue);
					startActivity(intent1);
				}
			});
		}
	}
	
	private final Handler mSaveScoreHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message pMsg) {
			if (mSaveProgressDialog != null) {
				mSaveProgressDialog.dismiss();
				mSaveProgressDialog = null;
			}
			
			if (pMsg.what == MSG_WHAT_SAVE_START)
				mSaveProgressDialog = ProgressDialog.show(SaveHighScoreAct.this, "Please wait", "Posting your score to server" , true , true);
			else if (pMsg.what == MSG_WHAT_SAVE_SUCCESS) {
				AlertDialog.Builder tBuilder = new AlertDialog.Builder(SaveHighScoreAct.this);
				tBuilder.setCancelable(true);
				tBuilder.setTitle("Success");
				tBuilder.setMessage("Score posted");
				tBuilder.show();
			}
			else if (pMsg.what == MSG_WHAT_SAVE_FAILED) {
				AlertDialog.Builder tBuilder = new AlertDialog.Builder(SaveHighScoreAct.this);
				tBuilder.setCancelable(true);
				tBuilder.setTitle("Failed");
				tBuilder.setMessage("Score post failed");
				tBuilder.show();
			}
		};
	};
	
	private ProgressDialog mSaveProgressDialog = null;
	private static final int MSG_WHAT_SAVE_START = 0;
	private static final int MSG_WHAT_SAVE_SUCCESS = 1;
	private static final int MSG_WHAT_SAVE_FAILED = 2;
	
	private void saveScore(final String pLevelName , final String pPlayerName , final int pScore , final Date pDateTaken) {
		Score.saveHighScore(getBaseContext(), new Score(pPlayerName , pLevelName, pScore, pDateTaken));
		Thread tScorePosterThread = new Thread() {
			@Override
			public void run() {
				mSaveScoreHandler.sendEmptyMessage(MSG_WHAT_SAVE_START);
				JSONObject tPostData = new JSONObject(); ///TODO: fill with post data
				if (RestClient.post("http://demeister.com/defenders/public/scripts/insert.php?level=" + pLevelName.replace(" " , "%20") + "&name=" + pPlayerName.replace(" ", "%20") + "&score=" + pScore, tPostData) != null) {
					mSaveScoreHandler.sendEmptyMessage(MSG_WHAT_SAVE_SUCCESS);
				}
				else
					mSaveScoreHandler.sendEmptyMessage(MSG_WHAT_SAVE_FAILED);
			}
		};
		
		tScorePosterThread.start();
	}
	
	private void promptPlayerName() {
		AlertDialog.Builder tBuilder = new AlertDialog.Builder(this);
		
		tBuilder.setTitle("Player Name");
		tBuilder.setMessage("Insert your name");
		
		final EditText tNameInput = new EditText(this);
		tBuilder.setView(tNameInput);
		
		tBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mPlayerName = tNameInput.getText().toString();
				if(mPlayerName.equals(""))
					Toast.makeText(getBaseContext(), "Please insert your name", 3000);
				else
					saveScore(mLevelName, mPlayerName, mScoreValue, mDateTaken);
			}
		});
		
		tBuilder.show();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		SoundManager.instance(getBaseContext()).temporarySetMute(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SoundManager.instance(getBaseContext()).temporarySetMute(false);
	}
	
	//SaveHighScorePanel
	private String	mLevelName;
	private int		mScoreValue;
	private Date	mDateTaken;
	private Button	mNextBtn;
	private EditText mPlayerNameEditTxt;
	
	private String 			mPlayerName = "Local Player";
	private TextView		mHighScoreValue, mLevelNameTextView;
	private Button			mFBShareBtn, mTwitterShareBtn, mPostScoreBtn;
	
	public static final String LEVEL_NAME_EXTRA		= "LEVEL_NAME";
	public static final String SAVE_OR_SHOW_EXTRA	= "SAVE_OR_SHOW";
	
	public static final int SAVE_SCORE_REQUEST = 0;
	public static final int SHOW_SCORE_REQUEST = 1;
	
	public static final int MAX_HIGH_SCORES = 5;
}
